﻿using Microsoft.AspNetCore.Mvc.Filters;
using System.Text.Json.Serialization;

namespace SimpleX
{
    public static partial class ServicesExtension
    {
        public static IServiceCollection AddControllers(this IServiceCollection services)
        {
            services.AddControllers(options =>
            {
                options.Filters.Add<UnifyResultFilter>();

                var actionFilters = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(IAsyncActionFilter))));

                foreach (var item in actionFilters)
                    options.Filters.Add(item);
            })
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
                options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals | JsonNumberHandling.AllowReadingFromString;// | JsonNumberHandling.WriteAsString;
                options.JsonSerializerOptions.WriteIndented = true;
            });

            services.AddRouting(options => options.LowercaseUrls = true);

            return services;
        }
    }
}